<template>
  <div class="base-date-range">
    <n-date-picker
      ref="elDatePicker"
      clearable
      type="datetimerange"
      @update:formatted-value="onUpdate"
      :value="defaultValue"
      v-bind="$attrs"
    ></n-date-picker>
  </div>
</template>

<script setup>
import { ref, watch } from 'vue'

const elDatePicker = ref(null)
const props = defineProps(['startDate', 'endDate'])
const emit = defineEmits(['update:startDate', 'update:endDate'])

const defaultValue = ref(null)

watch(
  () => props.startDate,
  () => {
    setTimeout(() => {
      if (!props.startDate) {
        elDatePicker.value.displayStartTime = ''
        elDatePicker.value.displayEndTime = ''
      } else {
        defaultValue.value = [
          new Date(props.startDate).getTime(),
          new Date(props.endDate).getTime(),
        ]
        elDatePicker.value.displayStartTime = props.startDate
        elDatePicker.value.displayEndTime = props.endDate
      }
    }, 0)
  },
  {
    immediate: true,
  }
)

function onUpdate(dateRange = []) {
  if (dateRange === null) {
    dateRange = []
  }

  const [startDate = '', endDate = ''] = dateRange
  emit('update:startDate', startDate)
  emit('update:endDate', endDate)
}
</script>

<style lang="scss" scoped>
.base-date-range {
  :deep(.n-date-picker) {
    width: 400px;
  }
}
</style>
